# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

# 读取文件夹中的文件，逐行解析
import os
import pprint



from gradio_client import Client, handle_file

from my_audio_client import MyAudioClient

my_audio_client = MyAudioClient()
config=my_audio_client.load_config()


def run(start_segment):
    # Use a breakpoint in the code line below to debug your script.


    lines = my_audio_client.read_file()
    rows = my_audio_client.parse_data(lines)
    blocks = my_audio_client.get_blocks(rows)
    role_dict = my_audio_client.get_role_dict(blocks)

    audio_path =my_audio_client.audio_path
    # 清空文件夹
    # util.delete_all_files(audio_path,start_segment)
    if not os.path.exists(audio_path):
        os.makedirs(audio_path)
    print(f"文件夹 {audio_path} 已创建")

    pprint.pp(role_dict)

    client = Client(config['gradio_url'],verbose=True)

    for role in role_dict.keys():
        if role in config['ignore_roles']:
            continue
        role_items=role_dict[role]
        for role_item in role_items:
            index = role_item['index']
            block = role_item['block']

            if config['test_block_num'] > 0:
                if index > config['test_block_num']:
                    break
            print('index', index,'block',block)
            if index<start_segment:
                continue
            print(index, len(blocks), len(block['text']), block)
            job_num=my_audio_client.geneAudioAsync(block,index, client)

            print('job_num',job_num)
            if job_num>config['max_job_num']:
                job_dict=my_audio_client.jobs.pop(0)
                print('job_dict',job_dict)
                my_audio_client.save_audio_async(job_dict["job"],job_dict["index"])

        jobs = my_audio_client.jobs
        print('jobs',len(jobs))

        i=len(blocks)-len(jobs)
        while len(jobs)>0:
            job_dict=jobs.pop(0)
            my_audio_client.save_audio_async(job_dict["job"],job_dict["index"])
            i+=1


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    start_segment = 0
    run(start_segment)
    print(f"生成音频的总时间：{my_audio_client.generate_audio_time_total} 秒")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
